package org.lmind.example.util;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;

public class URLs {

	/**
	 * @param args
	 */
	public static String relativePath(URL context, URL url) {
		
		if (!context.getHost().equals(url.getHost())) {
			return url.toString();
		}
		
		String s2 = relativePath(context.getFile(), url.getFile());
		
		if (!context.getHost().equals(url.getHost())) {
			s2 = url.getHost() + s2;
		}

		return s2;
	}
	
	
	public static String relativePath(String contextPath, String urlPath) {
		
		if (contextPath.equals("")) {
			contextPath = "/";
		}
		if (urlPath.equals("")) {
			urlPath = "/";
		}
		String s1 = contextPath.substring(0, contextPath.lastIndexOf("/") + 1);
		String s2 = urlPath.substring(0, urlPath.lastIndexOf("/") + 1);
		int index = sameParent(s1, s2).length();
		s1 = contextPath.substring(index);
		s2 = urlPath.substring(index);
		
		int count = Strings.occurrences(s1, "/");
		for (int i = 0; i < count; i++) {
			s2 = "../" + s2;
		}
		
		return s2;
	}
	
	public static URL url(String spec) throws MalformedURLException {
		URL url = new URL(spec);
		if ("".equals(url.getFile())) {
			return new URL(spec + "/");
		} else {
			return url;
		}
	}
	
	/**
	 * 构造一个URL对象,并修正如下bug：</br>
	 * <ul>
	 *   <li>
	 *   <p>当使用context=http://www.test.com/index.jsp和spec=?name=jack构造URL时,
	 *   得到了错误的结果http://www.test.com/?name=jack，
	 *   而正确的结果应该是http://www.test.com/index.jsp?name=jack,</p>
	 *   </li>
	 * </ul>
	 * @param context
	 * @param spec
	 * @return
	 * @throws MalformedURLException
	 */
	public static URL url(URL context, String spec) throws MalformedURLException {
		if (spec.startsWith("?")) {
			String file = URLs.file(context);
			file = file.replaceFirst("\\?.*$", "");
			file = file + spec;
			return new URL(context, file);
		}
		return new URL(context, spec);
	}
	
	public static String sameParent(String path1, String path2) {
		String same = path1.substring(0, Strings.same(path1, path2));
		int index = same.lastIndexOf("/");
		if (index == -1)
			return "";
		return same.substring(0, index + 1);
	}
	

	/**
	 * 
	 * @param url
	 * @return
	 */
	public static String file(URL url) {
		String file = url.getFile();
		return file.equals("") ? "/" : file;
	}

}
